package ionio.cscw.game;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckServlet extends HttpServlet {

	Database database = new Database();
	ListCheck listCheck;
	RepetitionCheck repetitionCheck=new RepetitionCheck();
	GibberishCheck gibberishCheck=new GibberishCheck();
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		try{
		listCheck=new ListCheck(config.getServletContext().getResource("/WEB-INF/wordlist.txt"));
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/plain");
		String[] query=req.getQueryString().split(";");
		String userId=query[0];
		String word=query[1].toUpperCase();
		String timestamp=query[2];
		if(query.length<=3) {
			int score=0;
			if(!gibberishCheck.checkWord(word)){
				score=-100;
			} else if(repetitionCheck.checkWord(word)){
				if(listCheck.checkWord(word)) {
					score=100;
				} else {
					score=200;					
				}
				
			}
			else{
				score=-50;
			}
			if (score>0) {
				database.storeData(Long.parseLong(userId), Long.parseLong(timestamp), word, 1);
			}
			resp.getWriter().println(score);
		} else {
			String totalScore=query[3];
			String nickname=query[4];
			database.storeScore(Long.parseLong(userId), nickname, Long.parseLong(totalScore),1);
		}
	}
	
}
